# tasks/basic_tasks.py
import time
import logging
import random
from datetime import datetime, timedelta
import requests
from typing import Dict, Any

logger = logging.getLogger(__name__)


class BasicTasks:
    """基础定时任务示例"""

    def __init__(self):
        self.execution_count = 0
        self.task_history = []

    def simple_interval_task(self, message: str = "默认消息") -> Dict[str, Any]:
        """简单间隔任务示例"""
        self.execution_count += 1
        task_id = f"simple_{datetime.now().strftime('%H%M%S')}"

        logger.info(f"执行简单间隔任务: {message}")

        try:
            # 模拟工作负载
            time.sleep(1)

            result = {
                'task_id': task_id,
                'message': message,
                'execution_count': self.execution_count,
                'timestamp': datetime.now().isoformat(),
                'status': 'success'
            }

            self.task_history.append(result)
            logger.info(f"简单任务完成: {result}")
            return result

        except Exception as e:
            error_result = {
                'task_id': task_id,
                'message': message,
                'error': str(e),
                'timestamp': datetime.now().isoformat(),
                'status': 'failed'
            }
            logger.error(f"简单任务失败: {error_result}")
            return error_result

    def data_collection_task(self, url: str = "https://httpbin.org/get") -> Dict[str, Any]:
        """数据收集任务示例"""
        logger.info(f"开始数据收集任务: {url}")

        try:
            start_time = time.time()

            # 模拟API调用
            response = requests.get(url, timeout=10)
            response.raise_for_status()

            collection_time = time.time() - start_time

            result = {
                'url': url,
                'status_code': response.status_code,
                'collection_time': collection_time,
                'data_size': len(response.content),
                'timestamp': datetime.now().isoformat()
            }

            logger.info(f"数据收集完成: 状态码{response.status_code}, 耗时{collection_time:.2f}秒")
            return result

        except Exception as e:
            logger.error(f"数据收集失败: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}

    def system_health_check(self) -> Dict[str, Any]:
        """系统健康检查任务"""
        logger.info("执行系统健康检查")

        try:
            # 模拟各种健康检查
            checks = {
                'disk_usage': random.randint(10, 90),  # 模拟磁盘使用率
                'memory_usage': random.randint(20, 80),  # 模拟内存使用率
                'cpu_load': random.uniform(0.1, 2.0),  # 模拟CPU负载
                'network_latency': random.uniform(1, 100)  # 模拟网络延迟
            }

            # 判断健康状态
            unhealthy_checks = []
            if checks['disk_usage'] > 85:
                unhealthy_checks.append('disk_usage')
            if checks['memory_usage'] > 80:
                unhealthy_checks.append('memory_usage')
            if checks['cpu_load'] > 1.5:
                unhealthy_checks.append('cpu_load')
            if checks['network_latency'] > 50:
                unhealthy_checks.append('network_latency')

            overall_status = 'healthy' if not unhealthy_checks else 'unhealthy'

            result = {
                'timestamp': datetime.now().isoformat(),
                'overall_status': overall_status,
                'unhealthy_checks': unhealthy_checks,
                'details': checks
            }

            status_msg = "健康" if overall_status == 'healthy' else f"异常: {unhealthy_checks}"
            logger.info(f"健康检查完成: {status_msg}")
            return result

        except Exception as e:
            logger.error(f"健康检查失败: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}

    def cleanup_task(self, max_age_hours: int = 24) -> Dict[str, Any]:
        """清理任务示例"""
        logger.info(f"开始清理任务，保留{max_age_hours}小时内数据")

        try:
            cutoff_time = datetime.now() - timedelta(hours=max_age_hours)

            # 模拟清理操作
            time.sleep(2)
            cleaned_count = random.randint(0, 1000)

            result = {
                'timestamp': datetime.now().isoformat(),
                'cutoff_time': cutoff_time.isoformat(),
                'cleaned_records': cleaned_count,
                'status': 'completed'
            }

            logger.info(f"清理完成: 删除{cleaned_count}条记录")
            return result

        except Exception as e:
            logger.error(f"清理任务失败: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}

    def batch_processing_task(self, batch_size: int = 100) -> Dict[str, Any]:
        """批量处理任务示例"""
        logger.info(f"开始批量处理，批次大小: {batch_size}")

        try:
            total_processed = 0
            batches = random.randint(1, 5)

            for i in range(batches):
                # 模拟批次处理
                time.sleep(0.5)
                processed = min(batch_size, random.randint(50, batch_size))
                total_processed += processed

                logger.info(f"批次 {i + 1}/{batches} 完成: 处理{processed}条")

            result = {
                'timestamp': datetime.now().isoformat(),
                'total_processed': total_processed,
                'batches': batches,
                'status': 'completed'
            }

            logger.info(f"批量处理完成: 共处理{total_processed}条记录")
            return result

        except Exception as e:
            logger.error(f"批量处理失败: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}

    def notification_task(self, recipient: str = "admin", message: str = "系统通知") -> Dict[str, Any]:
        """通知任务示例"""
        logger.info(f"发送通知给{recipient}: {message}")

        try:
            # 模拟发送通知
            time.sleep(1)

            result = {
                'timestamp': datetime.now().isoformat(),
                'recipient': recipient,
                'message': message,
                'status': 'sent'
            }

            logger.info("通知发送完成")
            return result

        except Exception as e:
            logger.error(f"通知发送失败: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}


# 创建任务实例
basic_tasks = BasicTasks()